package com.tanhua.server.service;

import com.tanhua.domain.mongo.Publish;
import com.tanhua.dubbo.api.PublishApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 关于动态相关的操作，通过RocketMQ发送消息，提供给大数据推荐系统使用的
 * @author liuyp
 * @date 2021/02/26
 */
@Slf4j
@Service
public class MovementsMQService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Reference
    private PublishApi publishApi;

    /**
     * 发布动态了，发送消息
     * @param publishId 动态id
     */
    public void savePublishMessage(String publishId){
        sendMessage(publishId, 1);
    }

    /**
     * 浏览动态了，发送消息
     * @param publishId 动态id
     */
    public void watchPublishMessage(String publishId){
        sendMessage(publishId, 2);
    }

    /**
     * 点赞动态了，发送消息
     * @param publishId 动态id
     */
    public void likePublishMessage(String publishId){
        sendMessage(publishId, 3);
    }

    /**
     * 喜欢动态了，发送消息
     * @param publishId 动态id
     */
    public void lovePublishMessage(String publishId){
        sendMessage(publishId, 4);
    }

    /**
     * 评论动态了，发送消息
     * @param publishId 动态id
     */
    public void commentPublishMessage(String publishId){
        sendMessage(publishId, 5);
    }

    /**
     * 取消点赞动态了，发送消息
     * @param publishId 动态id
     */
    public void unlikePublishMessage(String publishId){
        sendMessage(publishId, 6);
    }

    /**
     * 取消喜欢动态了，发送消息
     * @param publishId 动态id
     */
    public void dislovePublishMessage(String publishId){
        sendMessage(publishId, 7);
    }

    /**
     * 发送消息
     * @param publishId 动态id
     * @param type 操作类型
     *             1发动态；2浏览动态；3点赞；4喜欢；5评论；6取消点赞；7取消喜欢
     */
    public void sendMessage(String publishId, Integer type){
        //查询publishId对应的动态
        Publish publish = publishApi.findById(publishId);

        //构造消息对象
        Map<String, Object> message = new HashMap<>();
        message.put("userId", UserHolder.getUserId());
        message.put("publishId", publish.getPid());
        message.put("type", type);

        //发送消息
        rocketMQTemplate.convertAndSend("tanhua-quanzi", message);
        log.info("发送动态消息，供大数据推荐系统使用，topic：{}，消息：{}", "tanhua-quanzi", message);
    }

}
